package com.aleaho.cftrack.db.service;


import android.util.Log;

import com.aleaho.cftrack.CFTrackApplication;
import com.aleaho.cftrack.db.gen.UserDao;
import com.aleaho.cftrack.db.model.User;
import com.aleaho.cftrack.utils.Constants;

import java.util.List;

/**
 * Created by Administrator on 2017/10/2.
 */

public class UserService {


    private static UserDao userDao = CFTrackApplication.getInstance().getDaoSession().getUserDao();

    public static List<User> getUsers() {
        return userDao.loadAll();
    }


    /**
     * 获得给定用户信息
     *
     * @param username 用户名
     * @return 用户信息
     */
    public static String getUserInfo(String username) {
        List<User> users = null;
        try {
            users = userDao.queryBuilder().where(UserDao.Properties.Username.eq(username))
                    .orderDesc(UserDao.Properties.Id)
                    .list();
        } catch (Exception ex) {
            Log.e(Constants.TAG, ex.toString());
        }

        if (users == null || users.isEmpty())
            return "";
        else
            return users.get(0).getUserinfo();
    }


    /**
     * 获得给定用户的登录信息
     *
     * @param username 用户名
     * @return 用户的登录信息
     */
    public static User getUser(String username) {

        List<User> users = userDao.queryBuilder().where(UserDao.Properties.Username.eq(username))
                .orderDesc(UserDao.Properties.Id)
                .list();

        if (users.isEmpty())
            return null;
        return users.get(0);
    }


    public static void deleteByUserName(String username) {

        User user = getUser(username);
        if (user == null)
            return;
        userDao.delete(user);
    }


    public static void deleteAll() {
        userDao.deleteAll();
    }


    public static Long insert(String username, String userinfo) {

        deleteByUserName(username);

        return userDao.insert(new User(null, username, userinfo));
    }

}
